package com.yeskery.nut.extend.mybatis;

import com.yeskery.nut.core.NutException;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory;

import javax.sql.DataSource;

/**
 * 基于注解的MyBatis插件
 * @author sprout
 * @version 1.0
 * 2022-08-25 21:37
 */
public class AnnotationMyBatisPlugin extends BaseMyBatisPlugin {

    /**
     * 构建基于注解的MyBatis插件
     * @param basePackages 要扫描的基础包路径数组
     */
    public AnnotationMyBatisPlugin(String... basePackages) {
        super(new DefaultSqlSessionFactory(new Configuration()));
        setMyBatisScanBasePackages(basePackages);
    }

    /**
     * 构建基于注解的MyBatis插件
     * @param basePackages 要扫描的基础包数组
     * @param dataSource 数据源
     */
    public AnnotationMyBatisPlugin(String[] basePackages, DataSource dataSource) {
        super(new DefaultSqlSessionFactory(new Configuration()), dataSource);
        setMyBatisScanBasePackages(basePackages);
    }

    /**
     * 设置MyBatis扫描的基础路径
     * @param basePackages MyBatis扫描的基础路径
     */
    private void setMyBatisScanBasePackages(String[] basePackages) {
        if (basePackages == null || basePackages.length == 0) {
            throw new NutException("MyBatis Mapper Base Package Must Not Be Empty.");
        }
        Configuration configuration = getConfiguration();
        for (String basePackage : basePackages) {
            configuration.addMappers(basePackage);
        }
    }
}
